package cn.schoolwow.flow.monitor.module.initial.flow;

import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.entity.ConfigParameter;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.List;

public class SetConfigParameterFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(SetConfigParameterFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        List<ConfigParameter> configParameterList = flowMonitorOption.dao.query(ConfigParameter.class)
                .addQuery("enable", 1)
                .execute()
                .getList();
        for(ConfigParameter configParameter:configParameterList){
            try {
                Object instance = applicationContext.getBean(configParameter.getBeanName());
                JSONObject value = configParameter.getValue();

                QueryInstance queryInstance = QueryInstance.newQuery(instance);
                for(String key:value.keySet()){
                    queryInstance.setFieldValue(key, value.get(key));
                }
                queryInstance.execute();
                flowContext.putInstanceData(instance, FlowContextDataRange.Context);
            }catch (Exception e){
                logger.warn("加载配置类失败!bean名称:"+configParameter.getBeanName()+",原因:"+e.getMessage());
            }
        }
    }

    @Override
    public String name() {
        return "设置参数配置选项";
    }

}
